#include "config.h"

#ifdef ENABLE_POSTGRESQL

#include <iostream>

#include "PGSQLDatabase.h"
#include "PGSQLQuery.h"

/**
 *
 **/
PGSQLQuery::PGSQLQuery(PGSQLDatabase *dbc, PString database, PString sqlQuery) : AbstractQuery(dbc, database, sqlQuery)
{
    this->result = NULL;

    if(dbc->isConnected(*database))
    {
        boost::mutex::scoped_lock lock( dbc->queryLock );
        this->result = PQexec( dbc->connections[*database], sqlQuery->c_str() );

        int status = PQresultStatus(this->result);

        if(status == PGRES_TUPLES_OK || status == PGRES_COMMAND_OK )
        {
            this->num_rows = PQntuples(this->result);
        }
        else
        {
            String errorMessage = "status: ";
            errorMessage.append(boost::lexical_cast<String>(status));
            errorMessage.append("\n\r"
                                "error: ");
            errorMessage.append(PQerrorMessage(dbc->connections[*database]));
            errorMessage.append("\n\r"
                                "query: ");
            errorMessage.append(*sqlQuery);
            errorMessage.append("\n\r");
            std::cout << errorMessage << std::endl;
            this->result = NULL;
        }
        lock.unlock();
    }
}

/**
 *
 **/
PGSQLQuery::~PGSQLQuery(){
    if(this->result != NULL)
		PQclear(this->result);
}

/**
 *
 **/
PDataRow PGSQLQuery::fetch(){
	unsigned int field_count = PQnfields(result);
    for(unsigned int field_num=0; field_num < field_count; field_num++)
	{
		this->datarow->put( PQfname(this->result, field_num), PQgetvalue(this->result, (this->current_row-1), field_num) );
	}
	return this->datarow;
}
#endif
